package com.codeape.number.util;

import android.app.Application;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import com.codeape.number.R;
import com.codeape.number.entity.Result;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Objects;

public class DatabaseUtils {
    private static Application application;
    private static SQLiteDatabase guaDb, recordsDb;
    private static Cursor guaNameData, guaCiData, yaoCiData, yaoCiExplainData, recordsData;
    private static ArrayList<Integer> guaNumberList = new ArrayList<>();
    private static ArrayList<String> yaoCiList = new ArrayList<>();
    private static ArrayList<String> yaoCiExplainList = new ArrayList<>();

    public DatabaseUtils(Application application) {
        DatabaseUtils.application = application;
        new operationTask(application).execute();
    }

    private static SQLiteDatabase getDatabase(String databaseName) {
        return SQLiteDatabase.openOrCreateDatabase("/data" + Environment.getDataDirectory().getAbsolutePath() + "/com.codeape.number/app_databases" + "/" + databaseName, null);
    }

    public static Cursor getDatabaseTable(SQLiteDatabase database, String tableName, boolean isDesc) {
        Cursor cursor;
        if (isDesc) {
            cursor = database.query("records", null, null, null, null, null, "_id DESC");
        } else {
            cursor = database.query(tableName, null, null, null, null, null, null);
        }
        return cursor;
    }

    public static SQLiteDatabase getGuaDb() {
        return guaDb;
    }

    public static SQLiteDatabase getRecordsDb() {
        return recordsDb;
    }

    /**
     * 导入数字卦数据库
     *
     * @return SQLiteDatabase 返回数据库对象
     */
    private static SQLiteDatabase importDatabase() {
        String path = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/com.codeape.number/app_databases" + "/" + "shuzigua.db";
        try {
            if (!(new File(path).exists())) {
                // 判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
                InputStream is = application.getResources().openRawResource(R.raw.shuzigua); // 欲导入的数据库
                FileOutputStream fos = new FileOutputStream(path);
                int BUFFER_SIZE = 400000;
                byte[] buffer = new byte[BUFFER_SIZE];
                int count;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
            return SQLiteDatabase.openOrCreateDatabase(path, null);
        } catch (FileNotFoundException e) {
            Log.e("Database", "File not found");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("Database", "IO exception");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取计算结果
     *
     * @param resultCode 参数注释
     * @return String 返回内容注释
     */
    public static Result getCalculationResult(String resultCode) {

        for (int i = 0; i < guaNumberList.size(); i++) {
            if (guaNumberList.get(i) == Utils.AssemblyGua(Integer.parseInt(resultCode.substring(0, 2)))) {
                guaNameData.moveToPosition(i);
                guaCiData.moveToPosition(i);
                yaoCiData.moveToPosition(GetPosition(yaoCiList, Integer.valueOf(guaNameData.getString(0)), Integer.valueOf(resultCode.substring(2))));
                yaoCiExplainData.moveToPosition(GetPosition(yaoCiList, Integer.valueOf(guaNameData.getString(0)), Integer.valueOf(resultCode.substring(2))));
            }
        }

        return new Result(guaNameData.getString(1), guaCiData.getString(1), resultCode.substring(2), yaoCiData.getString(2), yaoCiExplainData.getString(2));
    }

    /**
     * 获取数据库游标
     */
    private static int GetPosition(ArrayList<String> list, int gua, int yao) {
        int tag = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals((String.valueOf(gua) + "-" + String.valueOf(yao)))) {
                tag = i;
                return tag;
            }
        }
        return tag;
    }

    private static class operationTask extends AsyncTask<String, Object, Long> {

        private final WeakReference<Application> application;

        private operationTask(Application application) {
            this.application = new WeakReference<>(application);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Long doInBackground(String... strings) {
            Application mApplication = application.get();
            // 是否建库
            if (Objects.equals(Utils.readSharedPreferences(application.get().getApplicationContext()), "")) {
                Utils.createDir("databases", 0, mApplication.getApplicationContext());

                Objects.requireNonNull(importDatabase()).close();

                Utils.saveSharedPreferences(mApplication.getApplicationContext());
            }

            guaDb = getDatabase("shuzigua.db");
            recordsDb = getDatabase("records.db");
            recordsDb.execSQL("create table if not exists records(_id integer primary key autoincrement,resultCode text,time text)");//创建表SQL语句并执行，创建表之前判断，多加了if not exists

            guaNameData = getDatabaseTable(guaDb, "gua", false);
            guaCiData = getDatabaseTable(guaDb, "guaci", false);
            yaoCiData = getDatabaseTable(guaDb, "yaoci", false);
            yaoCiExplainData = getDatabaseTable(guaDb, "yaocijd", false);
            recordsData = getDatabaseTable(recordsDb, "records", true);

            for (int i = 1; i <= 8; i++) {
                for (int j = 1; j <= 8; j++) {
                    guaNumberList.add(i * 10 + j);
                }
            }

            for (int i = 1; i <= 64; i++) {
                for (int j = 1; j <= 6; j++) {
                    yaoCiList.add(String.valueOf(i) + "-" + String.valueOf(j));
                    yaoCiExplainList.add(String.valueOf(i) + "-" + String.valueOf(j));
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Long aLong) {
            super.onPostExecute(aLong);
        }
    }

}